import { validatenull } from '@/utils/validate';
import { http } from '@/utils/http/axios';
import { storage } from '@/utils/Storage';
import { websiteConfig } from '@/config/website.config';
import { useUserStore } from '@/store/modules/user';
import qs from 'qs';
import { ContentTypeEnum } from '@/enums/httpEnum';

const scope = 'server';

/**
 * @description: 用户登录
 */
export function loginByUsername(username, password, code, randomStr) {
  const grant_type = 'password';
  const dataObj = qs.stringify({ username: username, password: password });
  //const dataObj = JSON.stringify({ username: username, password: password });
  const basicAuth = 'Basic ' + window.btoa(websiteConfig.formLoginClient);

  // 保存当前选中的 basic 认证信息
  storage.set('basicAuth', basicAuth);
  return http.request(
    {
      url: '/auth/oauth2/token',
      headers: {
        Authorization: basicAuth,
        'Content-Type': ContentTypeEnum.FORM_URLENCODED,
      },
      method: 'POST',
      params: { randomStr, code, grant_type, scope },
      data: dataObj,
    },
    {
      isTransformResponse: false,
      withToken: false,
    }
  );
}

export const loginByMobile = (smsForm) => {
  const grant_type = 'app';

  const basicAuth = 'Basic ' + window.btoa(websiteConfig.smsLoginClient);
  // 保存当前选中的 basic 认证信息
  storage.set('basicAuth', basicAuth);

  return http.request(
    {
      url: '/auth/oauth2/token',
      headers: {
        Authorization: basicAuth,
      },
      method: 'post',
      params: { phone: smsForm.phone, code: smsForm.code, grant_type, scope },
    },
    {
      isTransformResponse: false,
      withToken: false,
    }
  );
};

export const refreshToken = (refresh_token) => {
  const grant_type = 'refresh_token';
  // 获取当前选中的 basic 认证信息
  const basicAuth = storage.get('basicAuth');
  return http.request(
    {
      url: '/auth/oauth2/token',
      headers: {
        Authorization: basicAuth,
      },
      method: 'post',
      params: { refresh_token, grant_type, scope },
    },
    {
      isTransformResponse: false,
      withToken: false,
    }
  );
};
/**
 * @description: 用户登出
 */
export function logout() {
  return http.request({
    url: '/auth/token/logout',
    method: 'delete',
  });
}
/**
 * 校验令牌，若有效期小于半小时自动续期
 *
 * 定时任务请求后端接口返回实际的有效时间，不进行本地计算避免 客户端和服务器机器时钟不一致
 * @param refreshLock
 */
export const checkToken = (refreshLock, refreshTime) => {
  // 获取当前选中的 basic 认证信息
  //;
  const userStore = useUserStore();
  const token = userStore.getAccessToken;
  const basicAuth = storage.get('basicAuth');

  if (validatenull(userStore.getAccessToken) || validatenull(basicAuth)) {
    return;
  }

  http
    .request(
      {
        url: '/auth/token/check_token',
        headers: {
          isToken: false,
          Authorization: basicAuth,
        },
        method: 'get',
        params: { token },
      },
      {
        withToken: false,
      }
    )
    .then((response) => {
      const expire = response && response.data && response.data.exp;
      if (expire) {
        const expiredPeriod = expire * 1000 - new Date().getTime();
        console.log('当前token过期时间', expiredPeriod, '毫秒');
        //小于半小时自动续约
        if (expiredPeriod <= websiteConfig.remainingTime) {
          if (!refreshLock) {
            refreshLock = true;
            userStore.refreshToken().catch(() => {
              clearInterval(refreshTime);
            });
            refreshLock = false;
          }
        }
      }
    })
    .catch((error) => {
      console.error(error);
    });
};

/**
 * 注册用户
 */
export const registerUser = (userInfo) => {
  return http.request({
    url: '/admin/register/user',
    method: 'post',
    data: userInfo,
  });
};

/**
 * 发送短信
 */
export const sendSmsCode = (form) => {
  return http.request({
    url: '/admin/app/sms',
    method: 'post',
    data: form,
  });
};
